package com.newflypig.jblog.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.newflypig.jblog.service.ISystemService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
    @Autowired
    CustomSuccessHandler customSuccessHandler;
    
    @Autowired
    ISystemService systemService;
  
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	GeetestFilter geetestFilter = new GeetestFilter();
    	geetestFilter.setAuthenticationManager(this.authenticationManagerBean());
    	
    	CustomUserDetailsAuthenticationProvider authenticationProvider = new CustomUserDetailsAuthenticationProvider();
    	authenticationProvider.setSystemService(systemService);
    			
    	SimpleUrlAuthenticationFailureHandler hld = new SimpleUrlAuthenticationFailureHandler(){
    		@Override
    		public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
    				AuthenticationException exception) throws IOException, ServletException {
    			String message = exception instanceof BadCredentialsException ? "用户名密码错误！" : exception.getMessage();
    			request.getSession().setAttribute("exceptionMsg", message);
    			super.onAuthenticationFailure(request, response, exception);
    		}
    	};
    	
    	hld.setDefaultFailureUrl("/login?error");
    	geetestFilter.setAuthenticationFailureHandler(hld);
    	geetestFilter.setAuthenticationSuccessHandler(customSuccessHandler);
    	geetestFilter.setUsernameParameter("jblog_username");
    	geetestFilter.setPasswordParameter("jblog_password");
    	
    	http.addFilter(geetestFilter)
    		.authenticationProvider(authenticationProvider)
      		.authorizeRequests().antMatchers("/**/admin/**").access("hasRole('GUEST')")
      		.and().formLogin()
      			.loginPage("/login")
      		.and().csrf()
      		.and().logout()
      			.logoutUrl("/logout")
      			.logoutSuccessUrl("/")
      			.clearAuthentication(true)
      			.invalidateHttpSession(true);
    }
}
